/**
 * 
 */
package com.yangkun.test;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Company: </p> 
 * @author Administrator
 * @date 2017年7月28日
 */
import java.util.Date;
import java.util.Map;  

import org.springframework.web.socket.CloseStatus;  
import org.springframework.web.socket.TextMessage;  
import org.springframework.web.socket.WebSocketSession;  
import org.springframework.web.socket.handler.TextWebSocketHandler;  
  
public class MyHandler extends TextWebSocketHandler {  
  
	private Object t = null;
	
    @Override  
    public void afterConnectionEstablished(WebSocketSession session)  
            throws Exception {  
        System.out.println("connection established");  
        WebSocketSessionUtil.add(getUserNameFromSession(session), session);  
    }  
  
    @Override  
    public void handleTextMessage(WebSocketSession session, TextMessage message)  
            throws Exception {  
        System.out.println(session.getId()+"receive a message." + message);  
  
        WebSocketSessionUtil.broadcast(message); 
        if(t == null){
        	 new Thread(new Runnable(){

				@Override
				public void run() {
					int i = 1;
					while(true){
						TextMessage m = new TextMessage("server send:" + new Date());
						try{
						WebSocketSessionUtil.broadcast(m);  
						Thread.sleep(1000);
						}catch(Exception e){
							e.printStackTrace();
						}
						i++;
					}
					
				}
        		
        	}).start();
        	 
        	t = new Object();
        }
    }  
  
    @Override  
    public void handleTransportError(WebSocketSession session,  
            Throwable exception) throws Exception {  
        WebSocketSessionUtil.remove(getUserNameFromSession(session));  
    }  
  
    @Override  
    public void afterConnectionClosed(WebSocketSession session,  
            CloseStatus closeStatus) throws Exception {  
        System.out.println("conection closed." + closeStatus);  
  
        WebSocketSessionUtil.add(getUserNameFromSession(session), session);  
    }  
  
    @Override  
    public boolean supportsPartialMessages() {  
        return false;  
    }  
  
    private String getUserNameFromSession(WebSocketSession session) {  
        Map<String, Object> params = session.getAttributes();  
  
        return params.get("userName").toString();  
    }  
  
}  

